// pages/Storage/StoragePoolList.tsx
import React, { useEffect } from 'react';
import { useNavigate } from 'react-router-dom';
import { Plus, Play, Square, Trash2, Folder, Database } from 'lucide-react';
import { useStorageStore } from '../../stores/storageStore';
import { useApp } from '../../App';
import { ROUTES } from '../../router';
import type { StoragePoolSummary } from '../../types/api';

const StoragePoolList: React.FC = () => {
  const navigate = useNavigate();
  const { currentConnection } = useApp();
  const {
    storagePools,
    loading,
    error,
    fetchStoragePools,
    startStoragePool,
    stopStoragePool,
    deleteStoragePool
  } = useStorageStore();

  useEffect(() => {
    if (currentConnection) {
      fetchStoragePools(currentConnection);
    }
  }, [currentConnection, fetchStoragePools]);

  const handleStartPool = async (poolName: string) => {
    if (!currentConnection) return;
    try {
      await startStoragePool(currentConnection, poolName);
    } catch (error) {
      console.error('Failed to start storage pool:', error);
    }
  };

  const handleStopPool = async (poolName: string) => {
    if (!currentConnection) return;
    try {
      await stopStoragePool(currentConnection, poolName);
    } catch (error) {
      console.error('Failed to stop storage pool:', error);
    }
  };

  const handleDeletePool = async (poolName: string) => {
    if (!currentConnection) return;
    if (window.confirm(`Are you sure you want to delete storage pool "${poolName}"?`)) {
      try {
        await deleteStoragePool(currentConnection, poolName);
      } catch (error) {
        console.error('Failed to delete storage pool:', error);
      }
    }
  };

  const formatBytes = (bytes: number) => {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  };

  const getPoolStatus = (active: boolean) => {
    if (active) {
      return { color: 'text-green-500', bgColor: 'bg-green-500/10', label: 'Active' };
    } else {
      return { color: 'text-red-500', bgColor: 'bg-red-500/10', label: 'Inactive' };
    }
  };

  if (!currentConnection) {
    return (
      <div className="text-center py-12">
        <p className="text-lg text-gray-400 mb-4">No connection selected</p>
        <button
          onClick={() => navigate(ROUTES.CONNECTIONS)}
          className="px-4 py-2 bg-purple-600 hover:bg-purple-700 text-white rounded-lg transition-colors"
        >
          Go to Connections
        </button>
      </div>
    );
  }

  if (loading) {
    return (
      <div className="flex items-center justify-center h-64">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-purple-500"></div>
      </div>
    );
  }

  if (error) {
    return (
      <div className="text-center py-8">
        <p className="text-red-500 mb-4">{error}</p>
        <button
          onClick={() => fetchStoragePools(currentConnection)}
          className="px-4 py-2 bg-purple-600 hover:bg-purple-700 text-white rounded-lg transition-colors"
        >
          Retry
        </button>
      </div>
    );
  }

  return (
    <div>
      <div className="flex justify-between items-center mb-6">
        <h2 className="text-2xl font-bold">Storage Pools</h2>
        <button
          onClick={() => navigate(ROUTES.STORAGE)}
          className="flex items-center gap-2 px-4 py-2 bg-purple-600 hover:bg-purple-700 text-white rounded-lg transition-colors"
        >
          <Plus size={16} />
          New Pool
        </button>
      </div>

      {storagePools.length === 0 ? (
        <div className="text-center py-12">
          <Database className="mx-auto mb-4 text-gray-400" size={48} />
          <p className="text-lg text-gray-400 mb-4">No storage pools found</p>
          <button
            onClick={() => navigate(ROUTES.STORAGE)}
            className="px-4 py-2 bg-purple-600 hover:bg-purple-700 text-white rounded-lg transition-colors"
          >
            Create Pool
          </button>
        </div>
      ) : (
        <div className="grid gap-4">
          {storagePools.map((pool: StoragePoolSummary) => {
            const status = getPoolStatus(pool.active);
            const usagePercent = pool.capacity > 0
              ? Math.round(((pool.capacity - pool.available) / pool.capacity) * 100)
              : 0;

            return (
              <div
                key={pool.name}
                className="p-4 rounded-lg border border-gray-200 dark:border-gray-700 bg-white dark:bg-gray-900 hover:shadow-lg transition-all"
              >
                <div className="flex items-center justify-between mb-4">
                  <div className="flex items-center gap-4">
                    <div className="flex items-center gap-2">
                      <Folder size={20} className="text-blue-500" />
                      <div>
                        <h3 className="font-semibold">{pool.name}</h3>
                        <p className="text-sm text-gray-500">{pool.uuid}</p>
                      </div>
                    </div>
                    <div className="flex items-center gap-2">
                      <span className={`px-2 py-1 text-xs rounded ${status.bgColor} ${status.color}`}>
                        {status.label}
                      </span>
                    </div>
                  </div>

                  <div className="flex items-center gap-2">
                    {pool.active ? (
                      <button
                        onClick={() => handleStopPool(pool.name)}
                        className="p-2 text-yellow-500 hover:bg-yellow-500/10 rounded transition-colors"
                        title="Stop Pool"
                      >
                        <Square size={16} />
                      </button>
                    ) : (
                      <button
                        onClick={() => handleStartPool(pool.name)}
                        className="p-2 text-green-500 hover:bg-green-500/10 rounded transition-colors"
                        title="Start Pool"
                      >
                        <Play size={16} />
                      </button>
                    )}

                    <button
                      onClick={() => navigate(ROUTES.STORAGE_VOLUMES(pool.name))}
                      className="p-2 text-blue-500 hover:bg-blue-500/10 rounded transition-colors"
                      title="View Volumes"
                    >
                      <Folder size={16} />
                    </button>

                    <button
                      onClick={() => handleDeletePool(pool.name)}
                      className="p-2 text-red-500 hover:bg-red-500/10 rounded transition-colors"
                      title="Delete Pool"
                    >
                      <Trash2 size={16} />
                    </button>
                  </div>
                </div>

                <div className="mb-2">
                  <div className="flex justify-between text-sm text-gray-500 mb-1">
                    <span>Usage</span>
                    <span>{usagePercent}%</span>
                  </div>
                  <div className="w-full bg-gray-200 dark:bg-gray-700 rounded-full h-2">
                    <div
                      className="bg-blue-500 h-2 rounded-full transition-all"
                      style={{ width: `${usagePercent}%` }}
                    ></div>
                  </div>
                </div>

                <div className="flex justify-between text-sm text-gray-500">
                  <span>Capacity: {formatBytes(pool.capacity)}</span>
                  <span>Available: {formatBytes(pool.available)}</span>
                </div>
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
};

export default StoragePoolList;